import { API_CONFIG } from '../../../../config'
const { staticUrl } = API_CONFIG
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    staticUrl,
    // 下面为对接口后的数据
    ruleTitle: '活动规则',
    ruleBody: '', // 活动规则
    isShowPopups: false, // 是否显示邀请助力弹窗
    isTaskSuccess: false, // 是否显示任务完成弹窗
    isShowCreateTeam: false, // 是否显示创建队伍弹窗
    isShowAlreadyTeam: false, // 是否显示已有队伍弹窗
    isShowOvermanTeam: false, // 是否显示队伍人数已满弹窗
    btnStyle: '', // 全局按钮样式
    cardBtnText: '', // 商品卡片显示文字
    teamCardBtnText: '', // 组队卡片显示文字
    invitePopups: {}, // 邀请助力弹窗
    overman: {}, // 用户已满弹窗
    avatar: '', // 用户头像
    currentTeamInfo: {}, // 当前队伍详情
    memberData: [], // 当前队伍数据
    isComplete: -1, // 是否完成 1是0否
    status: -1, // 是否兑换  undefined为否 0,1皆为是
    teamCard: {
      middleBtnText: '',
      middleTitle: '邀请好友',
      rightCapsule: '历史记录',
      memberTotal: -1,
      timeArr: [
      ]
    },
    captainId: '', // 队长id
    currentUserId: '', // 当前用户id
    activityId: '', // 活动id
    appMsg: { type: 'err', show: false }, // 是否显示异常组件
    showPage: false,
    isOnShow: false,
    isCaptain: undefined
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.init(options)
  },
  onShow () {
    const { isOnShow } = this.data
    if (isOnShow) {
      this.reloadTeam()
    }
  },
  parseTeamDetails (arr) {
    // 拿出队长数据
    let leader = arr.filter(v => v.isCaptain === 1)
    let captainId = leader[0].id
    app.globalData.activityData.captainId = captainId
    // 拿出队员数据
    teammates = arr.filter(v => v.isCaptain !== 1)
    // 商品按钮内容
    let cardBtnText
    // 组队按钮内容
    let teamCardBtnText
    // 是否完成组队,显示不同按钮内容 1是 0否
    if (isComplete) {
      cardBtnText = inviteConfig.complete
    } else {
      cardBtnText = inviteConfig.notComplete
    }
    // 是否兑换,显示不同按钮内容
    if (status !== 2) {
      teamCardBtnText = inviteConfig.afterExchangeOrganize
      cardBtnText = inviteConfig.excahngeBtnContent
    } else {
      teamCardBtnText = inviteConfig.beforeExchangeOrganize
    }
    return [leader, ...teammates]
  },
  /**
   * @see 刷新队伍
   */
  reloadTeam () {
    const { activityId, isCaptain, captainId, inviteConfig } = this.data
    const request = { activityId, isCaptain, captainId }
    wx.$API['eventConfiguration/organizeDetails'](request).then(res => {
      let { data } = res
      if (!data.length) {
        this.setData({
          appMsg: { type: 'none', show: true }
        })
        this.createTeam({ isShowToast: true })
        wx.hideLoading()
        return
      }
      // 队友列表
      let { teammates } = data[0]
      // 是否兑换    是否完成     最大人数      当前用户id 是否是队长  
      let { status, isComplete, activityTarget, id, isCaptain } = data[0]
      this.data.isCaptain = isCaptain
      delete data[0].teammates
      // 数据整合
      let arr = [data[0], ...teammates]
      // 拿出队长数据
      let leader = arr.filter(v => v.isCaptain === 1)
      let captainId = leader[0].id
      app.globalData.activityData.captainId = captainId
      // 拿出队员数据
      teammates = arr.filter(v => v.isCaptain !== 1)
      // 商品按钮内容
      let cardBtnText
      // 组队按钮内容
      let teamCardBtnText
      // 是否完成组队,显示不同按钮内容 1是 0否
      if (isComplete) {
        cardBtnText = inviteConfig.complete
      } else {
        cardBtnText = inviteConfig.notComplete
      }
      // 是否兑换,显示不同按钮内容
      if (status !== 2) {
        teamCardBtnText = inviteConfig.afterExchangeOrganize
        cardBtnText = inviteConfig.excahngeBtnContent
      } else {
        teamCardBtnText = inviteConfig.beforeExchangeOrganize
      }
      arr = [...leader || arr[0], ...teammates]
      this.setData({
        captainId, // 队长id
        cardBtnText, // 卡片按钮显示内容
        teamCardBtnText, // 组队按钮显示内容
        teamCard: {
          middleBtnText: teamCardBtnText,
          middleTitle: '邀请好友',
          rightCapsule: '历史记录',
          memberTotal: activityTarget,
          status,
          timeArr: [
          ]
        },
        memberData: arr, // 组队数据
        isComplete: isComplete, // 是否完成
        status, // 是否兑换
        currentUserId: id, // 当前用户不一定是队长,所以要保存id
        appMsg: { show: false },
        showPage: true,
        isOnShow: true
      })
      wx.stopPullDownRefresh()
      wx.hideLoading()
    })
      .catch(error => {
        wx.hideLoading()
        wx.stopPullDownRefresh()
        wx.showToast({})
        console.log('下拉刷新出错', error);
      })
  },
  /**
   * @see 关闭弹窗
   */
  cancelPopups () {
    this.setData({
      isShowPopups: false
    })
  },
  init (options) {
    // 队长id,用来区分接下来是创建队伍还是加入队伍   后面的是活动id
    const { captainId, activityId } = app.globalData.activityData
    let { currentTeam } = options
    this.setData({
      // 保存用户头像
      avatar: options.avatar || 'https://xwx.gzzmedu.com:6899/pic/wx-x-mai/activity/defaultAvatar.png',
      // 保存活动id
      activityId,
      // 保存队长id
      captainId,
    })
    // 获取元素后再决定是创建还是加入队伍
    wx.showLoading({ title: '加载中' })
    this.getElements().then(() => {
      // 如果是从列表页查看详情
      if (currentTeam) {
        const { inviteConfig } = this.data
        //      队伍列表       队伍配置信息
        const { memberData, teamCard } = JSON.parse(currentTeam)
        //  是否兑换    是否完成    用户id 
        let { status, isComplete, id, isCaptain, captainId } = teamCard
        this.data.captainId = captainId // 保存队长id
        this.data.isCaptain = isCaptain // 是否是队长
        teamCard.middleTitle = '邀请好友'
        teamCard.rightCapsule = '历史记录'
        // 商品按钮内容
        let cardBtnText
        // 组队按钮内容
        let teamCardBtnText
        // 是否完成组队,显示不同按钮内容
        if (isComplete) {
          cardBtnText = inviteConfig.complete
        } else {
          cardBtnText = inviteConfig.notComplete
        }
        // 是否兑换,显示不同按钮内容 !==undefined即为已兑换
        if (status !== 2) {
          teamCardBtnText = inviteConfig.afterExchangeOrganize
          cardBtnText = inviteConfig.excahngeBtnContent
        } else {
          teamCardBtnText = inviteConfig.beforeExchangeOrganize
        }
        teamCard.middleBtnText = teamCardBtnText
        this.setData({
          memberData,
          teamCard,
          status,
          isComplete,
          cardBtnText,
          teamCardBtnText,
          currentUserId: id
        })
        wx.hideLoading()
      } else if (captainId) { // 加入队伍
        this.joinTheTeam()
        console.log('加入队伍');
      } else { // 创建队伍
        this.createTeam(options)
        console.log('创建队伍');
      }
    })
  },
  /**
   * @see 获取邀请助力配置
   */
  getElements () {
    // 活动id
    const { activityId } = app.globalData.activityData
    const btnStyle = wx.getStorageSync('activityBtnStyle')
    return new Promise((resolve, reject) => {
      wx.$API['eventConfiguration/getElements']({ activityId, eIndex: [3, 4, 8] })
        .then(res => {
          let invitePopups = {};
          let inviteConfig = {};
          let overman = {}
          if (!res.data.length) {
            this.setData({
              appMsg: { type: 'none', show: true }
            })
            wx.hideLoading()
            return
          }
          res.data.forEach(item => {
            let str = item.content
            switch (item.eindex) {
              case 3:
                inviteConfig = JSON.parse(str)
                break;
              case 4:
                invitePopups = JSON.parse(str)
                break;
              case 8:
                overman = JSON.parse(str)
                break;
              default:
                break;
            }
          })
          this.setData({
            invitePopups,
            inviteConfig,
            overman,
            staticUrl,
            topBgUrl: staticUrl + inviteConfig.bgImageUrl,
            cardImgUrl: staticUrl + inviteConfig.productUrl,
            ruleBody: inviteConfig.activityRules,
            // schedule: {
            //   isCarry: false,
            //   yesCarry: inviteConfig.complete,
            //   noCarry: inviteConfig.notComplete,
            // },
            isShowPopups: true,
            // 保存按钮样式
            btnStyle,
          })
          wx.hideLoading()
          resolve()
        })
        .catch(error => {
          wx.hideLoading()
          this.setData({
            appMsg: { type: 'err', show: true }
          })
          reject()
          console.log('eventConfiguration/getElements 获取邀请助力配置出错!', error)
        })
    })
  },
  /**
   * @see 创建队伍
   */
  createTeam (options) {
    // 用户信息
    const userInfo = wx.getStorageSync('userInfo')
    // 活动id
    const { activityId } = app.globalData.activityData
    // 用户头像
    const { avatar } = this.data
    // 是否显示提示消息
    const { isShowToast } = options
    const request = {
      username: userInfo.name, // 传递用户名
      userImage: avatar || 'https://xwx.gzzmedu.com:6899/pic/wx-x-mai/activity/defaultAvatar.png', // 传递头像
      activityId, // 传递活动id
    }
    // 请求创建队伍接口
    wx.$API['eventConfiguration/addManageOrganize'](request)
      .then((res) => {
        const { errcode, errmsg } = res
        if (errcode === '1012') {
          // console.log('显示已有队伍弹窗')
          isShowToast && this.setData({
            isShowAlreadyTeam: true,
            isShowPopups: false
          })
        } else if (errcode === '1013' || errcode === '1014' || errcode === '1015') {
          // console.log('显示提示')
          wx.showToast({
            title: errmsg,
            icon: 'none'
          })
        }
        else {
          // console.log('显示创建队伍弹窗', isShowToast, res)
          isShowToast && this.setData({
            isShowPopups: false, // 是否显示邀请助力弹窗
            isShowCreateTeam: true, // 是否显示创建队伍弹窗
            isShowAlreadyTeam: false, // 是否显示已有队伍弹窗
            isShowOvermanTeam: false, // 是否显示队伍人数已满弹窗
          })
        }
        this.getCurrentTeamInfo({ isComplete: 0 })
      })
      .catch(error => {
        wx.hideLoading()
        this.setData({
          isShowPopups: false, // 是否显示邀请助力弹窗
          isShowCreateTeam: false, // 是否显示创建队伍弹窗
          isShowAlreadyTeam: false, // 是否显示已有队伍弹窗
          isShowOvermanTeam: false, // 是否显示队伍人数已满弹窗
          ['teamCard.memberTotal']: 0
        })
        wx.showToast({
          title: error,
          icon: 'none',
          duration: 3000
        })
        console.log('eventConfiguration/addManageOrganize 创建队伍失败!', error)
      })
  },
  /**
   * @see 加入队伍
   */
  joinTheTeam () {
    const userInfo = wx.getStorageSync('userInfo')
    const { activityId } = this.data // 活动id
    const { avatar } = this.data // 用户头像
    const request = {
      activityId,
      userImage: avatar,
      username: userInfo.name,
      captainId: this.data.captainId
    }
    wx.$API['eventConfiguration/joinTheTeam'](request)
      .then(res => {
        const { errcode } = res
        let isComplete
        if (errcode === '1011') {
          // console.log('当前显示弹窗为队伍人数已满,返回值为:', res);
          isComplete = 0
          this.setData({
            isShowOvermanTeam: true,
            isShowPopups: false
          })
        } else if (errcode === '1010') { // 您已加入过其他队伍,或则队伍人数已满
          isComplete = res.result.isComplete
          // console.log('当前显示弹窗为已有队伍,返回值为:', res);
          isComplete !== 1 && this.setData({
            isShowAlreadyTeam: true,
            isShowPopups: false
          })
        } else if (errcode === '1016') {
          isComplete == 0
        } else {
          isComplete == 0
        }
        this.getCurrentTeamInfo({ isComplete })
      })
      .catch(error => {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '加入队伍失败',
          cancelText: '重试',
          confirmText: '创建队伍',
          success: res => {
            if (res.confirm) {
              this.createTeam({ isShowToast: true })
            } else if (res.cancel) {
              this.joinTheTeam()
            }
          }
        })
        console.log('eventConfiguration/joinTheTeam 加入队伍失败!', error)
      })
  },
  /**
   * @see 获取当前队伍信息
   */
  getCurrentTeamInfo ({ isComplete = 0 }) {
    return new Promise(resolve => {
      const { activityId, inviteConfig } = this.data
      const request = {
        activityId,
        isComplete,
      }
      wx.$API['eventConfiguration/listManageOrganize'](request)
        .then(res => {
          let { data } = res
          console.log('拿到当前队伍信息,返回值为', res)
          if (!data.length) {
            this.setData({
              appMsg: { type: 'none', show: true }
            })
            this.createTeam({ isShowToast: true })
            wx.hideLoading()
            return
          }
          // 队友列表
          let { teammates } = data[0]
          // 是否兑换    是否完成     最大人数      当前用户id 是否是队长  
          let { status, isComplete, activityTarget, id, isCaptain } = data[0]
          this.data.isCaptain = isCaptain
          delete data[0].teammates
          // 数据整合
          let arr = [data[0], ...teammates]
          // 拿出队长数据
          let leader = arr.filter(v => v.isCaptain === 1)
          let captainId = leader[0].id
          app.globalData.activityData.captainId = captainId
          // 拿出队员数据
          teammates = arr.filter(v => v.isCaptain !== 1)
          // 商品按钮内容
          let cardBtnText
          // 组队按钮内容
          let teamCardBtnText
          // 是否完成组队,显示不同按钮内容 1是 0否
          if (isComplete) {
            cardBtnText = inviteConfig.complete
          } else {
            cardBtnText = inviteConfig.notComplete
          }
          // 是否兑换,显示不同按钮内容
          if (status !== 2) {
            teamCardBtnText = inviteConfig.afterExchangeOrganize
            cardBtnText = inviteConfig.excahngeBtnContent
          } else {
            teamCardBtnText = inviteConfig.beforeExchangeOrganize
          }
          arr = [...leader || arr[0], ...teammates]
          this.setData({
            captainId, // 队长id
            cardBtnText, // 卡片按钮显示内容
            teamCardBtnText, // 组队按钮显示内容
            teamCard: {
              middleBtnText: teamCardBtnText,
              middleTitle: '邀请好友',
              rightCapsule: '历史记录',
              memberTotal: activityTarget,
              status,
              timeArr: [
              ]
            },
            memberData: arr, // 组队数据
            isComplete: isComplete, // 是否完成
            status: status, // 是否兑换
            currentUserId: id, // 当前用户不一定是队长,所以要保存id
            appMsg: { show: false },
            showPage: true,
            isOnShow: true
          })
          resolve()
          wx.hideLoading()
        })
        .catch(error => {
          wx.hideLoading()
          resolve()
          wx.showToast({
            title: error,
            icon: 'none'
          })
          console.log('eventConfiguration/listManageOrganize 获取当前队伍错误!', error)
        })
    })
  },
  /**
   * @see 判断当前状态,点击按钮触发什么行为
   */
  inviteFriends () {
    const { isComplete, status, currentUserId } = this.data
    if (isComplete === 1 && status === 2) {
      this.exchangeMask() // 兑换口罩
      // console.log('状态为任务完成,触发事件: 立即兑换口罩')
    } else if (isComplete === 0) {
      wx.navigateTo({
        url: `/pages/eventConfiguration/pages/searchIt/index?currentUserId=${currentUserId}`
      })
      // console.log('状态为未完成,触发事件: 邀请好友')
    } else if (status === 0) {
      wx.navigateTo({
        url: `/pages/eventConfiguration/pages/prizeCollection/index?id=${currentUserId}`
      })
      // console.log('已经提交过地址,触发事件为跳转到奖品领取页面 参数为:', currentUserId)
    } else if (status !== 2) {
      this.createTeam({ avatar: this.data.avatar, isShowToast: true })
      // console.log('状态为已兑换,未提交地址,触发事件: 创建更多队伍')
    }
  },
  // 选择触发什么事件
  chooseEvent () {
    const { isComplete, status } = this.data
    this.createTeam({ avatar: this.data.avatar, isShowToast: true })
    // console.log('状态为已兑换,触发事件: 创建更多队伍')
  },
  /**
   * @see 跳转到信息采集页面
   */
  exchangeMask () {
    const { currentUserId } = this.data
    wx.redirectTo({
      url: `/pages/eventConfiguration/pages/formCollection/index?currentUserId=${currentUserId}`
    })
  },
  /**
   * @see 点击添加队友
   */
  addPlayer () {
    const { teamCard, memberData } = this.data
    if (teamCard.memberTotal <= memberData.length) {
      wx.showToast({
        title: '当前队伍人数已满',
        icon: 'none'
      })
      return
    }
    wx.navigateTo({
      url: '/pages/eventConfiguration/pages/searchIt/index'
    })
  },

  /**
   * @see 点击复制事件
   */
  copySuccessBody (e) {
    const { successData } = this.data
    const index = e.currentTarget.dataset.index
    const { body } = successData[index]
    wx.setClipboardData({
      data: body,
      success: res => {
        console.log(res, '复制成功')
      },
      fail: err => {
        console.log(err, '复制失败')
      }
    })
  },
  /**
   * @see 关闭队伍人数已满弹窗
   */
  cancelOvermanTeam () {
    this.setData({
      isShowOvermanTeam: false
    })
    this.createTeam({ isShowToast: false })
  },
  /**
  * @see 关闭已有队伍弹窗
  */
  cancelAlreadyTeam () {
    this.setData({
      isShowAlreadyTeam: false
    })
  },
  /**
   * @see 关闭兑换口罩弹窗
   */
  cancelToaskSuccess () {
    this.setData({
      isTaskSuccess: false
    })
  },
  /**
   * @see 创建队伍弹窗
   */
  createTeamPopups () {
    // setTimeout(() => {
    this.setData({
      isShowCreateTeam: true
    })
    // }, 2000)
  },
  /**
   * @see 关闭创建队伍弹窗
   */
  cancelCreateTeam () {
    this.setData({
      isShowCreateTeam: false
    })
  },
  /**
   * @see 右上角胶囊按钮点击事件
   */
  capsuleClick () {
    wx.navigateTo({
      url: '/pages/eventConfiguration/pages/teamList/index'
    })
  },

  /**
   * @see 点击按钮触发事件
   */
  nextStep () {
    this.setData({
      isShowPopups: false
    })
    const { teamCard, memberData, currentUserId } = this.data
    if (teamCard.memberTotal <= memberData.length) {
      wx.showToast({
        title: '当前队伍人数已满',
        icon: 'none'
      })
      return
    }
    wx.navigateTo({
      url: `/pages/eventConfiguration/pages/searchIt/index?currentUserId=${currentUserId}`
    })
  },
  /**
   * @see 监听用户下拉动作
   */
  onPullDownRefresh () {
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    this.reloadTeam()
  },
})